/*
 * File: parser.cpp
 *
 * Written by Peter Horak in 2012 at Dartmouth College for the GreenCube project,
 * supervised by Professor Kristina Lynch.
 *
 * Purpose: parse binary data from the payload
 */

#include <iostream>
#include <string>

#include <stdint.h>

using namespace std;

// Used to find the start of each data group
const char sentinel = '$';
const char mag_sentinel = '#';

int main(int argc, char **argv)
{
    // To hold the data
    uint32_t time; // 4 bytes (unsigned int)
    int16_t data[10]; // 2 bytes each (short)
    char c; // 1 byte

    // Convert the data into text and output it to cout
    do {
        // Find the start of a line
        do {
            cin.read((&c),sizeof(c));
        } while ((c != sentinel) && (c != mag_sentinel));
        // Parse a full data line
        if (c == mag_sentinel)
        {
            cin.read(reinterpret_cast<char *>(&time),sizeof(time));
            cout << time << ' ';
            for (int i = 0; i < 10; i++)
            {
                cin.read(reinterpret_cast<char *>(&data[i]),sizeof(data[i]));
                cout << data[i] << ' ';
            }
            cout << endl;
        }
        // Parse a data line minus the mag components
        else
        {
            cin.read(reinterpret_cast<char *>(&time),sizeof(time));
            cout << time << ' ';
            for (int i = 0; i < 7; i++)
            {
                cin.read(reinterpret_cast<char *>(&data[i]),sizeof(data[i]));
                cout << data[i] << ' ';
            }
            // Print the previous mag values to make it easier to load into matlab
            for (int i = 7; i < 10; i++)
                cout << data[i] << ' ';
            cout << endl;
        }
    } while (cin && !cin.eof());
}
